# http://in.finitu.de/2008/11/01/reading-pdf-properties-with-ruby
# http://github.com/yob/pdf-reader/tree/master
# http://groups.google.com/group/pdf-reader

#!/usr/bin/ruby

require 'rubygems'
require 'pdf/reader'

	class MetaDataReceiver
    		attr_accessor :regular
    		attr_accessor :xml

    	def metadata(data)
      		@regular = data
    	end

    	def metadata_xml(data)
     		 @xml = data
    	end
  	end
	
	#parse pdf metadata
	def parse(f)
  		receiver = MetaDataReceiver.new
  		pdf = PDF::Reader.file(f, receiver, :pages => false, :metadata => true)
		#puts receiver.regular.inspect
  		metadata = receiver.regular.inspect
  		#puts receiver.xml.inspect
  		puts metadata.split(":")
		print ("----------\n\n")
		rescue PDF::Reader::MalformedPDFError => e
			print("\t*** #{e.message} ***\n\n")
		rescue PDF::Reader::UnsupportedFeatureError => e
			print("\t*** #{e.message} ***\n\n")
		rescue => e
			print("\t*** #{e.message} ***\n\n")
	end

	#loop through and print out pdf metadata
	def loop_metadata
		directory = ARGV
		files = Dir.glob("#{directory}/*")
			files.sort.each do |f| 
				print("FILENAME: #{f}\n")
				print("METADATA: \n")
				parse(f)
			end
	end

	#Just see which ones are unparsable by the gem
	def broken(f)
  		receiver = MetaDataReceiver.new
  		pdf = PDF::Reader.file(f, receiver, :pages => false, :metadata => true)
  		metadata = receiver.regular.inspect
		rescue PDF::Reader::MalformedPDFError => e
			print("\t#{f}--> #{e.message} \n")
		rescue PDF::Reader::UnsupportedFeatureError => e
			print("\t#{f}--> #{e.message} \n")
		rescue => e
			print("\t#{f}--> #{e.message} \n")
	end
	# Loop through and just report pdfs that are unparsable and display those
	def loop_broken
		directory = ARGV
		files = Dir.glob("#{directory}/*")
			print("Unreadable PDFs:\n")
			files.sort.each do |f| 
				broken(f)
			end
	end
	
	loop_metadata
	#loop_broken
